package com.ruoyi.develop.invoice.utils;

import com.ruoyi.develop.invoice.entity.NewInvoice;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class NewInvoiceExtractor {

//    public static Logger log = Logger.getLogger(Runnable.class);

    private static final String PDF_EXTENSION = ".pdf";


    /**
     * 处理指定文件夹中的PDF发票文件
     * @param folderPath 文件夹路径
     * @return 包含提取信息的 NewInvoice 列表
     */
    public static List<NewInvoice> newPdfProcessInvoicesInFolder(String folderPath) {
        File folder = new File(folderPath);

        File[] files = folder.listFiles();

        List<NewInvoice> resultList = new ArrayList<>();

        if (files != null) {
            for (File file : files) {
                if (isPdfFile(file)) {
                    NewInvoice result = extractInvoice(file.getAbsolutePath());

                    if (result != null) {
                        NewInvoice returnResult = createProcessedInvoice(result);
                        resultList.add(returnResult);
                    } else {
                        handleExtractionError(file);
                    }
                }
            }
        }

        return resultList;
    }


    /**
     * 处理指定的PDF发票文件
     * @param filePath 文件路径
     * @return 包含提取信息的 NewInvoice 列表
     */
    public static NewInvoice newPdfProcessInvoicesInFile(String filePath) {
        File file = new File(filePath);
        NewInvoice returnResult = new NewInvoice();
        if (isPdfFile(file)) {
            NewInvoice result = extractInvoice(file.getAbsolutePath());

            if (result != null) {
                returnResult = createProcessedInvoice(result);

            } else {
                handleExtractionError(file);
            }
        }

        return returnResult;
    }


    /**
     * 输出发票提取内容
     * @param invoiceList 发票提取结果集合
     */
    public static void newPrintListInvoice(List<NewInvoice> invoiceList, String type){
        int sum = 0;
        for (NewInvoice invoice : invoiceList) {
            sum++;
            if ("String".equals(type) || "string".equals(type)){
                System.out.println("\n文件绝对路径: " + invoice.getFileAbsolutePath() +
                        "\n发票号码: " + invoice.getNumber() +
                        "\n开票日期: " + invoice.getDate() +
                        "\n总价: " + invoice.getTotalAmount() +
                        "\n金额: " + invoice.getAmount() +
                        "\n税额: " + invoice.getTaxAmount() +
                        "\n销售方名称: " + invoice.getSellerName());
            } else if ("List".equals(type) || "list".equals(type)) {
                System.out.println(invoice);
            } else {
                System.out.println(invoice);
            }
        }
        System.out.println("\nTotal:" + sum);
    }


    /**
     * 检查文件是否为PDF文件
     * @param file 要检查的文件
     * @return 如果是PDF文件，返回 true，否则返回 false
     */
    private static boolean isPdfFile(File file) {
        return file.isFile() && file.getName().toLowerCase().endsWith(PDF_EXTENSION);
    }

    /**
     * 创建一个处理后的 NewInvoice 对象
     * @param result 原始的 NewInvoice 对象
     * @return 处理后的 NewInvoice 对象
     */
    private static NewInvoice createProcessedInvoice(NewInvoice result) {
        NewInvoice returnResult = new NewInvoice();
        returnResult.setFileAbsolutePath(result.getFileAbsolutePath());
        returnResult.setNumber(result.getNumber());
        returnResult.setDate(result.getDate());
        returnResult.setContent(result.getContent());
        returnResult.setTotalAmount(result.getTotalAmount());
        returnResult.setAmount(result.getAmount());
        returnResult.setTaxAmount(result.getTaxAmount());
        returnResult.setSellerName(result.getSellerName());
        returnResult.setInReserve2(result.getInReserve2());
        return returnResult;
    }


    /**
     * 处理提取失败的情况，输出错误信息
     * @param file 提取失败的文件
     */
    private static void handleExtractionError(File file) {
//        log.debug("文件: {}\t提取失败~~~\n"+ file.getName());
        System.out.println("文件: {}\t提取失败~~~\n"+ file.getName());
    }


    /**
     * 从本地文件或URL中提取发票信息。
     * @param filePath 本地文件路径或发票的URL。
     * @return 包含提取信息的 NewInvoice 对象。
     */
    private static NewInvoice extractInvoice(String filePath) {
        File sourceFile = new File(filePath);

        if (!sourceFile.exists()) {
//            log.error("指定的源文件不存在");
            System.out.println("指定的源文件不存在");
            //throw new IllegalArgumentException("指定的源文件不存在");
        }

        NewInvoice result = null;

        try {
            result = NewPdfInvoiceExtractor.extract(sourceFile);
            result.setFileAbsolutePath(sourceFile.getAbsolutePath());
        } catch (Exception e) {
            e.printStackTrace();
            result = new NewInvoice();
        }
        return result;
    }
}
